package com.rd.controller;

import com.rd.common.vo.AdminLoginVO;
import com.rd.pojo.Admin;
import com.rd.service.IAdminService;
import com.rd.util.ResultModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录控制器
 */
@Api(tags="LoginController")
@RestController
public class LoginController {

    @Resource
    private IAdminService adminService;

    @ApiOperation(value = "用户登录,成功返回token值")
    @PostMapping("/login")
    public ResultModel login(@RequestBody AdminLoginVO adminLoginVO, HttpServletRequest request){
     return adminService.login(adminLoginVO.getUsername(),adminLoginVO.getPassword()
             ,adminLoginVO.getCode(),request);
    }

    @ApiOperation(value = "获取当前登录的用户信息")
    @GetMapping("/adminInfo")
    public  Admin getAdminInfo(Principal principal){
        if(principal == null){
            return  null;
        }
        //获取用户名
        String username =principal.getName();
        //根据用户名获取用户详细信息
        Admin admin = adminService.getAdminInfo(username);
        admin.setPassword(null);
        // 根据用户id获取用户角色列表,返回admin
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public ResultModel logout(){
        return ResultModel.createBySuccess("注销成功！");
    }

}
